package com.qf.shiro;

import com.alibaba.druid.util.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * shiro权限会话管理
 */
public class AdminWebSessionManager extends DefaultWebSessionManager {

	public static final String LOGIN_TOKEN_KEY = "X-Dts-Admin-Token";
	private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

	/**
	 * 重写了获取UUID
	 * Cookie cookie = new Cookie (mysessionId,uuid)
	 * String uuid = cookie.getValue();
	 * 根据uuid获取对应的Session   uuid就是sessionId
	 * DefaultWebSessionManager:父亲就是上面的获取方法
	 * -----------------
	 * 现在：uuid 在请求头中
	 *
	 *
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@Override
	protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
		String id = WebUtils.toHttp(request).getHeader(LOGIN_TOKEN_KEY);
		if (!StringUtils.isEmpty(id)) {
			//判断请求头中是否有id 如果有 表示前端是Vue   异步
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
			return id;
		} else {
			//判断请求头中是否有id 如果没有 表示前端是jsp   同步
			return super.getSessionId(request, response);
		}
	}
}
